/*
 * @Date: 2019-12-2
 * @Author: xuechengwu <xuechengwu@erayt.com>
 * @Description: 品种叠加层
 */
import BaseLayer from './BaseLayer';
import { Bar } from './KBarLayer';
import Point from '../core/Point';
import MultiLine from '../base/MultiLine';
import Color from '../core/Color';

export default class OverlyingLayer extends BaseLayer {
  constructor(canvas, options) {
    super(canvas);
    this.width = options.width;
    this.height = options.height;
    this.xStep = options.xStep || 0;
    this.start = options.start || 0;
    this.end = options.end || 0;
    this.data = options.data || [];
  }

  /**
   * 渲染
   */
  make() {
    this.childs.splice(0, this.childs.length);
    if (this.data.length === 0) {
      return;
    }
    for (let i = 0; i < this.data.length; i++) {
      const overlying = this.data[i];
      let start = overlying.data.length - this.start;
      let end = overlying.data.length - this.end;
      let maxPrice = -1000000000000;
      let minPrice = 1000000000000;
      if (start < 0) {
        start = 0;
      }
      if (end < 0) {
        end = 0;
      }
      if (end === 0) {
        return;
      }
      for (let j = start; j <= end; j++) {
        if (overlying.data[j].high > maxPrice) {
          maxPrice = overlying.data[j].high;
        }
        if (overlying.data[j].low < minPrice) {
          minPrice = overlying.data[j].low;
        }
      }
      const yStep = this.height / (maxPrice - minPrice);
      if (overlying.lineType === 0) {
        /**柱图绘制开始**/
        for (let j = start; j <= end; j++) {
          const bar = new Bar(this.canvas, {
            bar: overlying.data[j],
            width: this.xStep,
            delta: yStep,
            baseLine: minPrice,
            redHollow: overlying.redHollow || false,
            greenHollow: overlying.greenHollow || true,
            redColor: overlying.redColor || '#0592FF',
            greenColor: overlying.greenColor || '#0592FF'
          });
          bar.setPosition( (j - start) * this.xStep, this.position.y);
          this.addChild(bar);
        }
      } else {
        const points = [];
        /**线图开始**/
        for (let j = start; j <= end; j++) {
          points.push(
            new Point(
              (j - start) * this.xStep,
              this.position.y + (overlying.data[j].close - min) * yStep
            )
          );
        }
        const line = new MultiLine(this.canvas, points);
        line.setLineWidth(2);
        line.setColor(new Color(overlying.lineColor));
        this.addChild(line);
        /**线图结束**/
      }
    }
  }
}
